package com.wwwarehouse.resource_center.fragment.rules;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.adapter.pop.BubblePopAdapter;
import com.wwwarehouse.common.bean.carddesk.CardDeskMessageStableCardBean;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.filter.SeriesBean;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.eventbus_event.DrawerSeriesCompleteEvent;
import com.wwwarehouse.common.fragment.DeskDrawerSeriesFragment;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.adapter.rules.TasksBuidNamesBean;
import com.wwwarehouse.resource_center.bean.goods.SerializableMap;
import com.wwwarehouse.resource_center.bean.rules.RuleDesk;
import com.wwwarehouse.resource_center.bean.rules.StocksBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.Event;
import com.wwwarehouse.resource_center.eventbus_event.HideTitleBean;
import com.wwwarehouse.resource_center.eventbus_event.RulesEvent;
import com.wwwarehouse.resource_center.fragment.base.MyBaseViewPagerFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Joseph on 2017/11/10.
 *         <p/>
 *         编辑任务分配规则滑动界面,规则列表，信息卡和功能卡通用
 */
@Route(path = ResourceConstant.INFOMATION_TASK_RULES)
public class EditTaskRuleFragment extends MyBaseViewPagerFragment {

    private static final int SEARCH_TASK_ALLOCATION_RULE_DESKTOP = 1;
    public static final int GET_DISTRIBUT_ABLE_STOCKS = 2;  //获取未分配的应用对象
    int mNum = 8;
    private String searchRuleName ;
    private  String   mSort = "UPDATE_TIME DESC" ;
    private List<FilterBean> sortList; //排序
    private String businessId;
    private ArrayList<StocksBean.ListBean> stocksListBeen;  //应用对象
    private ArrayList<String>  applyBusinessList = new ArrayList<>();
    private ArrayList<String>  mBusinessNames = new ArrayList<>();
    private Map<String, Object> map;
    private List<SeriesBean> mFiltList;
    List<FilterBean> filterStocksBeen = new ArrayList<>(); //应用对象
    List<FilterBean> filterBuidsBeen = new ArrayList<>(); //应用单位
    private ArrayList<String> businessIdList = new ArrayList<>();//业务单位集合
    private boolean  isFunction = true ;// 是功能卡还是信息卡，true  功能卡
    private ArrayList<TasksBuidNamesBean> tasksBeanBuidNames;
    private String mTitle ;
    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    public void sortClick(View anchor) {
        if (peekFragment() instanceof EditTaskRuleFragment ){
            PopUpUtils.showBubbleDown(anchor, mActivity, sortList, new BubblePopAdapter.OnPopListClickListener() {
                @Override
                public void setOnItemClickListener(int i, View view) {
                    switch (i) {
                        case 0:
                            mSort = "UPDATE_TIME DESC";      //时间倒序
                            sortList.get(0).setSelect(true);
                            sortList.get(1).setSelect(false);
                            break;
                        case 1:
                            mSort = "UPDATE_TIME ASC";        //时间
                            sortList.get(0).setSelect(false);
                            sortList.get(1).setSelect(true);
                            break;
                        default:
                            break;
                    }
                    //接口请求
//                    if (stocksListBeen != null && stocksListBeen.size() > 0) {
//                        applyBusinessList = new ArrayList<>();
//                        for (int i1 = 0; i1 < stocksListBeen.size(); i1++) {
//                            applyBusinessList.add(stocksListBeen.get(i1).getStockUkid());
//                        }
//                    }
                    getRuleDesk(searchRuleName,mSort,businessIdList,applyBusinessList);
                }
            });
        }
    }
    @Override
    public void cancelClick() {
        super.cancelClick();
        searchRuleName = "";
        getRuleDesk(searchRuleName,mSort,businessIdList,applyBusinessList);
    }
    @Override
    public void searchNoRealTimeClick(String text) {
        if (peekFragment() instanceof EditTaskRuleFragment){
            searchRuleName = text;
            getRuleDesk(searchRuleName,mSort,businessIdList,applyBusinessList);
        }
    }
    @Override
    public void filterClick() {
        if (peekFragment() instanceof EditTaskRuleFragment) {
            ((BaseCardDeskActivity) mActivity).showDrawerLayout();
        }
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof EditTaskRuleFragment){

            mActivity.setTitle(mTitle);
        }
    }

    @Override
    public void onDownPull() {
        if (isShow){
            ((BaseCardDeskActivity)mActivity).showSearchTitle();
        }else {
            ((BaseCardDeskActivity)mActivity).hideSearchTitle();
        }
        isShow = !isShow;
    }

    protected void loadDatas() {
        Bundle bundle = getArguments();
        if (null!=bundle){
            CardDeskFunctionResponseBean.TaskBean taskBean = (CardDeskFunctionResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS);
            if (taskBean!=null){
                //功能卡
                mTitle = getString(R.string.edit_task_rule);
                isFunction = true;
                businessId = taskBean.getBusinessId();
                businessIdList.add(businessId);
            }else {
                isFunction = false;
                //信息卡
                mTitle = getString(R.string.configuring_task_rules);
                CardDeskMessageStableCardBean.TasksBean tasksBean = bundle.getParcelable("data");
                if (tasksBean != null) {
                    List<CardDeskMessageStableCardBean.TasksBeanBuidNames> tasksBeanBuidName = tasksBean.getTasksBeanBuidNames();
                    String s = JSON.toJSONString(tasksBeanBuidName);
                     tasksBeanBuidNames = (ArrayList<TasksBuidNamesBean>) JSON.parseArray(s, TasksBuidNamesBean.class);
                    if (this.tasksBeanBuidNames !=null&& this.tasksBeanBuidNames.size()>0){
                        for (int i = 0; i < this.tasksBeanBuidNames.size(); i++) {
                            businessIdList.add(this.tasksBeanBuidNames.get(i).getId());
                            mBusinessNames.add(this.tasksBeanBuidNames.get(i).getName());
                            filterBuidsBeen.add(new FilterBean(false, this.tasksBeanBuidNames.get(i).getName()));
                        }
                    }
                }
            }
        }
        sortList = new ArrayList<>();
        FilterBean filterBean = new FilterBean(true,"修改时间近到远");
        FilterBean filterBean1 = new FilterBean(false,"修改时间远到近");
        sortList.add( filterBean);
        sortList.add( filterBean1);
    }
    @Override
    public void requestDatas() {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> baseQueryMap = new HashMap<>();
        baseQueryMap.put("page",1);
        baseQueryMap.put("size",-1);  //查所有
        baseQueryMap.put("sort","UPDATE_TIME DESC");
        map.put("businessIdList", businessIdList);
        map.put("baseQuery", baseQueryMap);
        httpPost(ResourceConstant.GET_DISTRIBUT_ABLE_STOCKS,map,GET_DISTRIBUT_ABLE_STOCKS,false,"");
    }

    public void onEventMainThread(Event event) {
        if (event.getCode()==RulesEvent.RULE_REFRESH){
            //刷新页面数据
            getRuleDesk("",mSort,businessIdList,applyBusinessList);
        }
        else if (event.getData() instanceof HideTitleBean && event.getCode() == HideTitleBean.CODE.A) {
            isShow = true;
        }
    }

    public void onEventMainThread(RulesEvent event) {
      if (event.getCode()==RulesEvent.RULE_DRAWER_LINKAGE){
          Map<String,ArrayList<String>>  listMap = (Map<String, ArrayList<String>>) event.getData();
          if (null==listMap){
              if (this.tasksBeanBuidNames !=null&& this.tasksBeanBuidNames.size()>0){
                  for (int i = 0; i < this.tasksBeanBuidNames.size(); i++) {
                      businessIdList.add(this.tasksBeanBuidNames.get(i).getId());
                  }
              }
              applyBusinessList = new ArrayList<>();
              for (int i = 0; i < stocksListBeen.size(); i++) {
                  applyBusinessList.add(stocksListBeen.get(i).getStockUkid());
              }
              //重置到前一个状态
//                resetStatus();
          }else {
              businessIdList =  listMap.get("businessIdList");
              applyBusinessList =  listMap.get("applyBusinessList");
          }
          getRuleDesk(searchRuleName,mSort,businessIdList,applyBusinessList);
      }
    }
    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        switch (what) {
            case SEARCH_TASK_ALLOCATION_RULE_DESKTOP:
                if (TextUtils.equals("0", commonClass.getCode())) {
                    RuleDesk  desks  =  JSON.parseObject(commonClass.getData().toString(), RuleDesk.class);
                    int total = desks.getTotal();
                    if (total<=0){
                        mLoadingView.setVisibility(View.VISIBLE);
                        mLoadingView.showEmptyView(true);
                        mLoadingView.setEmptyListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mLoadingView.showProgressView(true);
                                getRuleDesk("",mSort,businessIdList,applyBusinessList);
                            }
                        });
                        return;
                    }
                    Bundle bundle = new Bundle();
                    SerializableMap myMap = new SerializableMap();
                    myMap.setMap(map);//将map数据添加到封装的myMap中
                    bundle.putSerializable("map", myMap);   //type
                    bundle.putBoolean("isFunction",isFunction);
                    SetFragmentAndPage(total,mNum,new EditTaskRuleListFragment().getClass().getName(),bundle);

                }
                break;
            case GET_DISTRIBUT_ABLE_STOCKS:
                if (TextUtils.equals("0", commonClass.getCode())) {
                    StocksBean stocksBean = JSON.parseObject(commonClass.getData().toString(), StocksBean.class);
                    stocksListBeen = (ArrayList<StocksBean.ListBean>) stocksBean.getList();
                    if (stocksListBeen != null && stocksListBeen.size() > 0) {
                        applyBusinessList = new ArrayList<>();
                        for (int i1 = 0; i1 < stocksListBeen.size(); i1++) {
                            applyBusinessList.add(stocksListBeen.get(i1).getStockUkid());
                            filterStocksBeen.add(new FilterBean(false,stocksListBeen.get(i1).getStockName()));
                        }
                        mFiltList = new ArrayList<>();
                        if (!isFunction){
                            DrawerLinkageScreenFragment deskDrawerMultipleFragment = new DrawerLinkageScreenFragment();
                            Bundle  bundle = new Bundle();
                            bundle.putParcelableArrayList("tasksBeanBuidNames", tasksBeanBuidNames);
                            bundle.putParcelableArrayList("stocksListBeen",stocksListBeen);
                            bundle.putStringArrayList("businessIdList",businessIdList);
                            bundle.putStringArrayList("applyBusinessList",applyBusinessList);
                            deskDrawerMultipleFragment.setArguments(bundle);
                            ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerMultipleFragment);
                        }else {
                            SeriesBean seriesBean1 = new SeriesBean();
                            seriesBean1.setCount(1);
                            seriesBean1.setSingle(false);
                            seriesBean1.setTitle("应用对象");
                            seriesBean1.setList(filterStocksBeen);
                            mFiltList.add(seriesBean1);
                            DeskDrawerSeriesFragment deskDrawerMultipleFragment = DeskDrawerSeriesFragment.newInstance(mFiltList);
                            ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerMultipleFragment);
                        }
                        getRuleDesk("",mSort,businessIdList,applyBusinessList);
                    }else {
                        mLoadingView.setVisibility(View.VISIBLE);
                        mLoadingView.showEmptyView(true);
                        mLoadingView.setEmptyListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mLoadingView.showProgressView(true);
                                requestDatas();
                            }
                        });
                        return;

                    }
                    break;
                }
        }
    }
    //获取规则列表
    public void getRuleDesk(String searName,String  sort,ArrayList<String> businessIdList,ArrayList<String> applyBusinessList) {
        searchRuleName = searName;
        map = new HashMap<>();
        Map<String, Object> baseQueryMap = new HashMap<>();
        baseQueryMap.put("page",1);
        baseQueryMap.put("size",1);
        baseQueryMap.put("sort",sort);
        map.put("applyBusinessList", applyBusinessList);    //应用对象(即仓库)
        map.put("searchRuleName", searchRuleName);        //搜索名称
        map.put("businessIdList", businessIdList);         //选择的业务单位
        map.put("baseQuery",baseQueryMap);
        httpPost(ResourceConstant.SEARCH_TASK_ALLOCATION_RULE_DESKTOP, map,SEARCH_TASK_ALLOCATION_RULE_DESKTOP,false,null);//规则桌面
    }
    public void onEventMainThread(DrawerSeriesCompleteEvent event) {
        if (peekFragment() instanceof EditTaskRuleFragment) {
            if (event.isReset()){
                applyBusinessList = new ArrayList<>();
                for (int i = 0; i < stocksListBeen.size(); i++) {
                    applyBusinessList.add(stocksListBeen.get(i).getStockUkid());
                }
                //重置到前一个状态
//                resetStatus();
                ((BaseCardDeskActivity) mActivity).hideDrawerLayout();
            }else {
                //完成
                mFiltList = event.getList();
                filterStocksBeen = mFiltList.get(0).getList();
                boolean flag = true;
                for (int i = 0; i < filterStocksBeen.size(); i++) {
                    if (filterStocksBeen.get(i).isSelect()) {
                        if (flag) {
                            applyBusinessList = new ArrayList<>();
                            flag = false;
                        }
                        applyBusinessList.add(stocksListBeen.get(i).getStockUkid());
                    }
                }
                if (flag) {
                    applyBusinessList = new ArrayList<>();
                    for (int i = 0; i < stocksListBeen.size(); i++) {
                        applyBusinessList.add(stocksListBeen.get(i).getStockUkid());
                    }
                }
                //请求接口
            }
            getRuleDesk(searchRuleName,mSort,businessIdList,applyBusinessList);
        }
    }

    @Override
    protected void receiveEvent(Event event) {
        if (event.getData() instanceof HideTitleBean && event.getCode() == HideTitleBean.CODE.A) {
            isShow = true;
        }
    }

    @Override
    public void onReLoad(int code) {
        this.requestDatas();
    }
}
